package com.raph.message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.Base64;

public class Message {
    private String type;
    private String content;
    private byte[] fileContent;

    public Message() {

    }

    public Message(String json) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(byte[].class, new ByteArrayToBase64Adapter())
                .create();
        Message message = gson.fromJson(json, Message.class);
        this.type = message.getType();
        this.content = message.getContent();
        this.fileContent = message.getFileContent();
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public byte[] getFileContent() {
        return fileContent;
    }

    public void setFileContent(byte[] fileContent) {
        this.fileContent = fileContent;
    }

    @Override
    public String toString() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(byte[].class, new ByteArrayToBase64Adapter())
                .create();
        return gson.toJson(this);
    }

    private static class ByteArrayToBase64Adapter extends TypeAdapter<byte[]> {
        @Override
        public void write(JsonWriter out, byte[] value) throws IOException {
            if (value == null) {
                out.nullValue();
                return;
            }
            String base64 = Base64.getEncoder().encodeToString(value);
            out.value(base64);
        }

        @Override
        public byte[] read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull(); // 消费 null 值
                return new byte[0];    // 返回 Java null
            } else {
                String base64 = in.nextString();
                return Base64.getDecoder().decode(base64);
            }
        }
    }
}
